/*
浅拷贝：
 */

// 1. ...实现
let copy1 = {...{x:1}}

// 2. Object.assign实现
let copy2 = Object.assign({}, {x:1})

/*
深拷贝：
 */
// 1. JOSN.stringify()/JSON.parse()
// 缺点：拷贝对象包含 正则表达式，函数，或者undefined等值会失败
let obj = {a: 1, b: {x: 3}}
JSON.parse(JSON.stringify(obj))

// 2. 递归拷贝
function deepClone(source){
    let target = null
    if(typeof source === 'object'){
        target = (Object.prototype.toString.call(source)==='[object Array]') ? [] :{}
        for(let key in source){
            target[key] = deepClone(source[key])
        }
    }else {
        target = source
    }
    return target
}




let object1 = {
    num:1,
    str:'string',
    nul:null,
    bool:true,
    regexp:new RegExp('string'),
    undef:undefined,
    arr:[1,'1','string',[1,'1','sting'],{
        num:1,
        arr:[1,{
            num:1
        }]
    }],
    obj:{
        num:1,
        str:'string',
        arr:[1,'1','string',[1,'1','string'],{num:1,arr:[1]}]
    },
    fn:function(){
        console.log(1+2)
        return 'func1'
    }
}


Object.prototype.deepClone = function() {
    return deepClone(this);
};
Object.defineProperty(Object.prototype, 'deepClone', {enumerable: false});

let object2 = object1.deepClone()

object2.num = 2
object2.arr[0] = 2
object2.arr[1] = '2'
object2.arr[3][0] = 2
object2.arr[4].num = 2
object2.arr[4].arr[0] = 2
object2.arr[4].arr[1].num = 2
object2.obj.num = 2
object2.obj.arr[0] = 2
object2.obj.arr[3][0] = 2
object2.obj.arr[4].num = 2
object2.obj.arr[4].arr[0] = 2
//object2.fn = function(){return "func2"}

console.log(object1,object2)
console.log(JSON.stringify(object1))
console.log(JSON.stringify(object2))
console.log(object1.fn(),object2.fn())
console.log(object1.fn,object2.fn)

